package pers.gxm.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.gxm.shiro.pojo.User;
import pers.gxm.shiro.service.UserService;

import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    /**
     * 自定义授权方法
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入自定义授权方法");
//        TODO 1 获取请求的用户名
        String username = principals.getPrimaryPrincipal().toString();
//        TODO 2 从数据库获取角色数据
        List<String> roles = userService.getUserRoles(username);
//        TODO 2.1 从数据库获取权限数据
        List<String> permissions = userService.getPermissionsByRole(roles);
//        TODO 3 创建授权信息对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        TODO 4 将角色数据封装进入授权信息对象内
        authorizationInfo.addRoles(roles);
//        TODO 5 将权限数据封装入授权信息对象内
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 自定义认证方法
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//  TODO 1  获取用户输入的身份信息
        String name = token.getPrincipal().toString();
//  TODO 2  从数据库中获取UserDetail
        User user = userService.getUserByName(name);
//  TODO 3  验证密码是否正确
        if(user != null){
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    token.getPrincipal(),user.getPwd(), ByteSource.Util.bytes("myPassword"),token.getPrincipal().toString()
            );
            return info;
        }
        return null;
    }
}
